iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
Software Development

clojure 30 days系列 第 22

clojure 30 days - day 20

  • 分享至 

  • xImage
  •  

Problem Description

Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer.

Square all numbers k (0 <= k <= n) between 0 and n.

Count the numbers of digits d used in the writing of all the k**2.

Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.

Examples:
n = 10, d = 1
the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.

nb_dig(25, 1) returns 11 since
the k*k that contain the digit 1 are:
1, 16, 81, 100, 121, 144, 169, 196, 361, 441.
So there are 11 digits 1 for the squares of numbers between 0 and 25.
Note that 121 has twice the digit 1.

Note

  • keywords
    • range: creates a sequence of numbers
    • inc: adds 1 (because range excludes the end number)
    • map: applies a function to every item in a collection
    • #(* % %): anonymous function shorthand for squaring
    • str: converts numbers to strings
    • apply: applies a function to all items (here, joins strings)
    • filter: keeps only items that match a condition
    • let: creates local variables for cleaner code

Implementation

; implement
(defn nb-dig [n d]
  (let [squares (map #(* % %) (range (inc n)))
        square-strings (map str squares)
        target-digit (str d)
        all-digits (apply str square-strings)]
    (count (filter #(= % target-digit) all-digits))))

; test
; execute implement function
(defn tester [n d exp]
  (= (nb-dig n d) exp))

; args & exceptio
(comment
  (tester 10 1 4) 
  (tester 25 1 11)     
  (tester 5750 0 4700)
  (tester 11011 2 9481) 
  (tester 12224 8 7733) 
  (tester 11549 1 11905))

上一篇
clojure 30 days - day 19
下一篇
clojure 30 days - day 21
系列文
clojure 30 days25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言